package com.shadow.study.h2;

import com.shadow.study.h2.service.H2UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.Environment;

import javax.annotation.Resource;

@Slf4j
@SpringBootApplication
public class H2App {

    @Resource
    private H2UserMapper userMapper;

    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(H2App.class, args);
        log.info("系统启动成功");
        Environment env = run.getEnvironment();
        String port = env.getProperty("server.port");
        String contextPath = env.getProperty("server.servlet.context-path");
        String path = "http://localhost:" + port + contextPath;
        log.info("数据库地址: {}", path + "/h2-console");
        log.info("测试1, 查询: {}", path + "/user/get");
        log.info("测试2, 新增: {}", path + "/user/add");
    }

    // 监听应用启动完成事件，检查并创建表
    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        if (userMapper.checkTableExists() == 0) {
            userMapper.createTable();
            log.info("Table created.");
        } else {
            log.info("Table already exists.");
        }
    }
}
